define(["mock", "allTpl", "lazyload", "page", "dropload"], function (Mock, template, lazyload, CutScreen, dropload) {

    var keyword_val = decodeURI(parse_url(window.location.href)['keyword']),
        key_word = typeof (keyword_val) === "undefined" ? "" : keyword_val;

    var _param_ = {
        page: 1,
        size: 100,
        from_price: 0, //价格区间
        to_price: 0,  //价格区间
        brand_id: 0, //品牌id
        key_word: key_word , //一个关键词用key_word
        order_by: 0, // 0正序 1倒序  价格最低开始就从传1
        order_key: "综合", //排序关键词
        category3_id: parse_url(window.location.href)['id'], //三级分类id
        "request": ""  //多个关键词用request
    };
    var dropme;
    var isEnd = false;

    //__base.url.list.search = "http://10.0.10.59:9000/listPage";

    return {
        init: function () {
            var G = this;
            G.Box = $("#box_listPage");
            G.ListBox =  G.Box.find(".listBox");
            G.Data = null;
            G.pageIndex = 0;
            G.Request = [];
            G.PriceOrder = 0;
            window.Dropload = null;
            G.isNotData = true; // 如果找不到商品就不让用户筛选

            G.listAjax = function (option, success, error) {
                var opt = $.extend({
                    page: 1,
                    size: 8,
                    from_price: 0, //价格区间
                    to_price: 0,  //价格区间
                    brand_id: 0, //品牌id
                    key_word: typeof (keyword_val) === "undefined" && "", //一个关键词用key_word
                    order_by: 0, // 0正序 1倒序  价格最低开始就从传1
                    order_key: "价格", //排序关键词
                    category3_id: parse_url(window.location.href)['id'], //三级分类id
                    "request": ""  //多个关键词用request
                }, _param_);

                __base.AjaxFun({
                    url: __base.url.list.search,
                    data: opt
                }, function (data) {
                    if (data["Code"] === "0") {
                        ajaxLoading.remove();
                        G.Data = data;
                        success(data);
                    } else {
                        typeof (error) === "function" && error();
                    }
                })
            };

            G.readerList.call(G);

            var $topMenu_Global = $(".topMenu_Global");
            $topMenu_Global.find("div:eq(0)").on('click', function () {
                G.pageIndex = 0;
                _param_ = {
					page: 1,
					size: 8,
					from_price: 0, //价格区间
					to_price: 0,  //价格区间
					brand_id: 0, //品牌id
					key_word: key_word, //一个关键词用key_word
					order_by: 0, // 0正序 1倒序  价格最低开始就从传1
					order_key: "综合", //排序关键词
					category3_id: parse_url(window.location.href)['id'], //三级分类id
					"request": ""  //多个关键词用request
				};
                $(".dropload-down").remove();
                G.loadData(_param_,dropme);
                G.ListBox.html("");
            });

            $topMenu_Global.find("div:eq(1)").on('click', function () {

                var $iconPrice = $("#listPage .icon-price");
            	_param_.order_key = "价格";
            	_param_.page = 1;
                $(".dropload-down").remove();
                G.ListBox.html("");
                //$("#box_listPage").remove();
                //$("#sectionBox_listPage").append('<section id="box_listPage" class="listBox01_Global"> <div class="listBox"></div> </section>')

                if (_param_.order_by === 1) {
                    _param_.order_by = 0;
                    $iconPrice.removeClass("current");
                } else {
                    $iconPrice.addClass("current");
                    _param_.order_by = 1;
                }
                popWrap.alert({content:"正在加载，请稍后",autoClose:false});
				G.loadData(_param_,dropme);	
            });

            $topMenu_Global.find("div:eq(2)").on('click', function () {
                // 如果找不到商品就不让用户筛选
                if (!G.isNotData){
                    G.filter.call(G);
                }
            });

        },

        //筛选功能
        filter:function(){

            var G = this,
                $indexPage = $("#index_section");

            if (!$indexPage.find(".filter_listPage")[0]){
                var html_filter = template('Reservation/listPage/filter_listPage', G.Data["Data"]);
                $indexPage.html(html_filter);
            }


            var $section_container = $("#section_container"),
                $sectionBox_listPage = $("#sectionBox_listPage"),
                $filterBox_listPage = $("#filterBox_listPage"),
                $filter_listPage = $(".filter_listPage");

            $filterBox_listPage.show();
            $sectionBox_listPage.hide();

            $filterBox_listPage.find(".sidebar").on('click', function () {
                $filterBox_listPage.hide();
                $sectionBox_listPage.show();
            });

            //筛选页面提交
            $indexPage.find(".btnBlue").on('click', function () {
                var brandId = $indexPage.find("li[data-target=brand_filter_listPage]").data("checked"),
                    from_price = Number($indexPage.find("li[data-target=price_filter_listPage]")
                        .data("from_price")),
                    to_price = Number($indexPage.find("li[data-target=price_filter_listPage]").data("to_price")),
                    request = function () {
                        var ls = [];
                        $indexPage.find("li[data-target=category_filter_listPage]").each(function (k, k_item) {
                            if ($(k_item).data("request")) {
                                $.each($(k_item).data("request"), function (o, o_item) {
                                    ls.push(o_item);
                                });
                            }
                        });
                        //console.log(ls);
                        return ls;
                    };

                var json = {
                    brand_id: brandId ? brandId[0] : 0,
                    from_price: from_price || 0,
                    to_price: to_price || 0,
                    "request": request().length === 0 ? "" : JSON.stringify(request())
                };
                //console.log(json);

                $filterBox_listPage.hide();
                $sectionBox_listPage.show();


                //$(".dropload-down").remove();
                G.ListBox.html("");
                popWrap.alert({content:"正在加载，请稍后",autoClose:false});

                _param_.page =1;
                _param_.brand_id = json.brand_id;
                _param_.from_price = json.from_price;
                _param_.to_price = json.to_price;
                _param_.request = json.request;
                G.loadData(_param_,dropme);
            });

            //筛选页面选项绑定功能
            $filter_listPage.find(".content li").each(function () {
                var targetElem = $(this),
                    targetDom = $(this).attr("data-target"),
                    targetData = $(this).attr("data-itemId");

                if (targetData) {
                    targetData = G.Data["Data"]["screening"] &&　G.Data["Data"]["screening"][targetData]
                } else {
                    targetData = G.Data["Data"]
                }


                //筛选分类切换
                $(this).CutScreen({
                    template: true,
                    init: function ($dom_filter) {
                        var _this = this;
                        var html_brand = template('Reservation/listPage/' + targetDom, targetData);
                        $dom_filter.html(html_brand);

                        if (targetElem.data("checked")) {
                            if (targetDom === "brand_filter_listPage" || targetDom === "price_filter_listPage") {
                                $dom_filter.find(".content li").each(function () {
                                    //console.log($(this).attr("data-id"));
                                    if ($(this).attr("data-id") === targetElem.data("checked")[0]) {
                                        $(this).addClass("contentOn").find("span[class^=icon]")
                                            .attr("class", "icon-on").html("&#xe925;");
                                    }
                                });

                            } else {
                                $dom_filter.find(".content li").each(function (i, item) {
                                    $.each(targetElem.data("checked"), function (j, j_item) {
                                        if ($(item).attr("data-id") === j_item) {
                                            //console.log($(item).attr("data-id"), j_item);
                                            $(item).addClass("contentOn").find("span[class^=icon]")
                                                .attr("class", "icon-on").html("&#xe925;");
                                        }
                                    });


                                });
                            }
                        }

                        $dom_filter
                            .one("click", ".icon-back", function () {
                                _this.back($(this));
                            })
                            .one("click", ".btn_sidebar", function () {
                                $("#index_section").show();
                                _this.close($(this));
                            });

                        $dom_filter.on("click", ".content li", function () {
                            if (targetDom === "brand_filter_listPage" || targetDom === "price_filter_listPage") {

                                if ($(this).hasClass("contentOn")) {
                                    $(this).removeClass("contentOn").find(".icon-on").attr("class", "icon-next")
                                        .html("&#xe91f;");
                                } else {
                                    $dom_filter.find(".contentOn").removeClass("contentOn").find(".icon-on")
                                        .html("");
                                    $(this).addClass("contentOn").find("span[class^=icon]")
                                        .attr("class", "icon-on").html("&#xe925;");
                                }

                            } else {
                                if ($(this).hasClass("contentOn")) {
                                    $(this).removeClass("contentOn").find(".icon-on").attr("class", "icon-next")
                                        .html("&#xe91f;");
                                } else {
                                    $(this).addClass("contentOn").find("span[class^=icon]")
                                        .attr("class", "icon-on").html("&#xe925;");
                                }
                            }

                        })

                        //分类提交按钮事件
                        .on("click", ".contTop i, .btnBlue", function () {
                            var ls_name = [],
                                ls_id = [],
                                $contentOn = $dom_filter.find(".contentOn");

                            if (targetDom === "brand_filter_listPage" || targetDom === "price_filter_listPage") {
                                ls_name.push($contentOn.find(".til").text());
                                ls_id.push($contentOn.attr("data-id"));

                                if (targetDom === "price_filter_listPage") {
                                    targetElem.data("from_price", $contentOn.attr("data-fromPrice"));
                                    targetElem.data("to_price", $contentOn.attr("data-toPrice"));
                                    console.log(targetElem, $contentOn.attr("data-fromPrice"), $contentOn.attr("data-toPrice"));
                                }

                            } else {
                                $dom_filter.find(".contentOn").each(function (i, item) {
                                    ls_name.push($(item).find(".til").text());
                                    ls_id.push($(item).attr("data-id"));
                                });

                            }

                            if (ls_id[0]) {
                                targetElem.data("checked", ls_id).find(".con").text(ls_name.join(" | "));
                                targetElem.data("request", ls_name);
                            } else {
                                targetElem.data("checked", []).data("request", []).find(".con").html("全部");
                            }

                            _this.back($(this));

                        })


                    }


                });
            });
        },

        //load
        loadData : function(json,me) {
        	var G = this;
		    G.listAjax(json, function (data) {
                popWrap.alertRemove();
		
		        if (G.Data["Data"]["product"] === null) {
		            if ( G.ListBox.html() !== "" ) {
		                --_param_.page;
		                isEnd = true;
		                return false;
		            } else {
                        G.Box.find(".dropload-down").remove();
                        G.ListBox.html(_CONFIG[__webState].noProductData.addClass("absolute"));
		                $("#sectionBox_listPage").find(".nf-pro-content .btn").on('click', function () {
		                    $(".topMenu_Global").find("div:eq(0)").trigger("click");
		                });
                        G.isNotData = true;
                        return false;
		            }
		        }
                G.isNotData = false;

		        //G.pageIndex++;
				++_param_.page;
		        console.log(G.pageIndex, data);
		        var html = template('Reservation/listPage/box_listPage', G.Data["Data"])
		            .replace(/%URL%/g, _CONFIG[__webState].goodsPage_URL);
		
		        // 为了测试，延迟1秒加载
		        //setTimeout(function () {
		        G.Box.find(".listBox").append(html);
		        // 每次数据加载完，必须重置
		        me.resetload();
		        //}, 3000);
		        // 每次数据加载完，必须重置
		        $(".lazyImg").lazyload({
		            effect: "fadeIn",
		            threshold: 150
		        });
		
		    });
		},
        
        //生成列表
        readerList: function (jsonObj) {
            var G = this,
                json = null;

            $(window).scrollTop(0);
            G.topIcon();

            var $box_listPage = $('#box_listPage');

            window.Dropload =  $box_listPage.dropload({
                scrollArea: window,
                domDown: {      // 下方DOM
                    domClass: 'dropload-down',
                    domRefresh: '<div class="dropload-refresh">↑上拉加载更多</div>',
                    domLoad: '<div class="dropload-load"><span class="loading"></span>加载中...</div>',
                    domNoData: '<div class="dropload-noData">已经是最后一页了</div>'
                },
                loadDownFn: function (me) {

                    if (isEnd) {
                        me.isData = false;
                        me.lock("down");
                        me.resetload();
                        return false;
                    }
                    if (typeof (jsonObj) === "undefined") {
                        json = {
                            page: G.pageIndex + 1
                        };
                    } else {
                        json = $.extend({
                            page: G.pageIndex + 1
                        }, jsonObj);
                    }

          /*          // 每加载完3页就显示点击加载更多
                    if (/^[1-9]\d*$/.test(G.pageIndex / 3)) {
                        me.lock("up");
                        me.resetload();
                        $(".dropload-down").html('<div class="dropload-click">点击继续加载</div>');
                        $(".dropload-click").on("click", function () {
                        	G.loadData(_param_,me)
                        });
                        return false;
                    } else {

                        G.loadData(_param_,me)
                    }*/


                    G.loadData(_param_,me);

					dropme = me;


                }
            });


        },

        //顶部按钮
        topIcon: function () {
            var G = this;
            if (!$(".topIcon")[0]) {
                var $goToTop = $('<div class="topIcon" style="display: none;"><img src="../../assets/images/Reservation/indexPage/topIcon.png" ></div>');
                $goToTop.on('click', function () {
                    $(window).scrollTop(0);
                });
                G.Box.append($goToTop);
                $(window).scroll(function () {
                    if ($(this).scrollTop() > 200) {
                        $goToTop.fadeIn(300);
                    } else {
                        $goToTop.fadeOut(300)
                    }
                })
            }
        }
    }
});

